package com.ww.editsms.db;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.text.TextUtils;
import android.util.Log;

import com.ww.editsms.entity.Person;
import com.ww.editsms.entity.SMS;
import com.ww.editsms.util.SmsUtil;

public class Cursordb {
	/** 联系人显示名�?**/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;
	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;
	/** 头像ID **/
	private static final int PHONES_PHOTO_ID_INDEX = 2;
	/** 联系人的ID **/
	private static final int PHONES_CONTACT_ID_INDEX = 3;

	public static List<Person> getPersonList(Context context, List<String[]> list) {
		List<Person> persons = new ArrayList<Person>();
		for (int i = 0; i < list.size(); i++) {
			Person p = getPhoneContacts(context, list.get(i)[0]);
			p.setCount(list.get(i)[1]);
			String[] ss = getSmsInPhone(context, list.get(i)[0], list.get(i)[2]);
			if (SmsUtil.isNotEmpty(ss[0])) {
				p.setDesc(ss[0]);
				p.setTime(ss[1]);
				persons.add(p);
			}
		}
		return persons;
	}

	public static List<Person> getPhoneContacts(Context mContext) {
		List<Person> list = new ArrayList<Person>();
		ContentResolver resolver = mContext.getContentResolver();
		// 获取手机联系�?
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {
				Person p = new Person();
				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				// 当手机号码为空的或�?为空字段 跳过当前循环
				if (TextUtils.isEmpty(phoneNumber))
					continue;
				// 得到联系人名�?
				String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
				// 得到联系人ID
				Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
				// 得到联系人头像ID
				Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
				// 得到联系人头像Bitamp
				Bitmap contactPhoto = null;
				// photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他�?��默认�?

				if (photoid > 0) {
					Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactid);
					InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
					contactPhoto = BitmapFactory.decodeStream(input);
				}
				p.setName(contactName);
				p.setNumber(phoneNumber);
				p.setPhoto(contactPhoto);
				list.add(p);
			}
			phoneCursor.close();
		}
		return list;
	}

	/**
	 * 封装首页信息列表.
	 * 
	 * @param context
	 *            Context
	 * @return List<Person>
	 */
	public static List<String[]> getAllPhone(Context context) {
		List<String[]> list = getPersons(context);
		return list;
	}

	/**
	 * 获取短信中联系人列表（包括：号码，最后一条短信时间，短信总数�?
	 * 
	 * @param context
	 *            Context
	 * @return List<String[号码�?短信总数，最后一条短信时间]>
	 */
	public static List<String[]> getPersons(Context context) {
		List<String[]> list = new ArrayList<String[]>();
		Cursor cur = null;
		try {
			ContentResolver cr = context.getContentResolver();
			cur = cr.query(Uri.parse("content://sms/"), new String[] { "count(*) as count", "address", "thread_id",
					"date" }, "1=1) group by (address", null, "date desc");
			if (cur.moveToFirst()) {
				String phoneNumber;
				int dateColumn = cur.getColumnIndex("date");
				int phoneNumberColumn = cur.getColumnIndex("address");
				do {
					String[] str = new String[3];
					phoneNumber = cur.getString(phoneNumberColumn);
					if (phoneNumber != null) {
						str[0] = phoneNumber;
						str[1] = cur.getLong(0) + "";
						str[2] = cur.getString(dateColumn);

						str[0].trim();
						if (str[0].startsWith("+86")) {
							str[0].replace("+86", "");
						}


						if (ccc(list, str[0])) {
							list.add(str);
						}
					}
				} while (cur.moveToNext());
			} else {
			}

		} catch (SQLiteException ex) {
			Log.d("SQLiteException in getSmsInPhone", ex.getMessage());
		} finally {
			if (cur != null) {
				cur.close();
			}
		}
		return list;
	}

	private static boolean ccc(List<String[]> list, String str) {
		boolean bool = true;
		//Logger.info("str:"+str);
		for (int i = 0; i < list.size(); i++) {
			//Logger.info("list.get(i)[0]:"+list.get(i)[0]);
			if (list.get(i)[0].equals(str)) {
				//Logger.info("ccc   true");
				bool = false;
				break;
			}
		}
		return bool;
	}

	/**
	 * 根据号码获取联系人详�?
	 * 
	 * @param context
	 *            Context
	 * @param phoneNum
	 *            号码
	 * @return Person
	 */

	private static final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID,
			Phone.CONTACT_ID };

	public static Person getPhoneContacts(Context context, String phoneNum) {
		Person p = new Person();
		String contactName = "";
		ContentResolver cr = context.getContentResolver();
		Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION,
				ContactsContract.CommonDataKinds.Phone.NUMBER + " = ? or "
						+ ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[] { phoneNum }, null);
		if (pCur.moveToFirst()) {
			contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			Long photoid = pCur.getLong(PHONES_PHOTO_ID_INDEX);
			p.setNumber(phoneNum);
			p.setName(contactName);
			Bitmap contactPhoto = null;
			if (photoid > 0) {
				// 得到联系人ID
				Long contactid = pCur.getLong(PHONES_CONTACT_ID_INDEX);
				Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactid);
				InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
				contactPhoto = BitmapFactory.decodeStream(input);
				p.setPhoto(contactPhoto);
			}
		} else {
			p.setNumber(phoneNum);
			p.setName(phoneNum);
		}
		
		if(pCur!=null){
			pCur.close();
		}
		return p;
	}

	/**
	 * 根据号码和最后一条短信的时间获取短信内容.
	 * 
	 * @param context
	 *            Context
	 * @param phone
	 *            号码
	 * @param date时间
	 * @return String[内容，时间]
	 */
	public static String[] getSmsInPhone(Context context, String phone, String date) {
		final String SMS_URI_ALL = "content://sms/";
		StringBuilder smsBuilder = new StringBuilder();
		String[] ss = new String[2];
		Cursor cur = null;
		try {
			ContentResolver cr = context.getContentResolver();
			String[] projection = new String[] { "_id", "thread_id", "address", "person", "body", "date", "type" };
			Uri uri = Uri.parse(SMS_URI_ALL);
			cur = cr.query(uri, projection, " (address=? or address=?) and date=?", new String[] { phone,
					"+86" + phone, date }, "date asc");
			if (cur.moveToFirst()) {
				String smsbody;
				int smsbodyColumn = cur.getColumnIndex("body");
				int dateColumn = cur.getColumnIndex("date");
				do {
					smsbody = cur.getString(smsbodyColumn);
					ss[0] = smsbody;
					ss[1] = cur.getString(dateColumn);
				} while (cur.moveToNext());
			} else {
				smsBuilder.append("no result!");
			}

			smsBuilder.append("getSmsInPhone has executed!");
		} catch (SQLiteException ex) {
			Log.d("SQLiteException in getSmsInPhone", ex.getMessage());
		} finally {
			if (cur != null) {
				cur.close();
			}
		}
		return ss;
	}

	public static List<SMS> getSmsInPhone(Context context, String phone) {
		final String SMS_URI_ALL = "content://sms/";
		List<SMS> list = new ArrayList<SMS>();
		Cursor cur = null;
		try {
			ContentResolver cr = context.getContentResolver();
			String num = phone;
			if (phone.startsWith("+86")) {
				num = phone.replace("+86", "");
			} else {
				num = "+86" + phone;
			}
			String[] projection = new String[] { "_id", "thread_id", "address", "person", "body", "date", "type" };
			Uri uri = Uri.parse(SMS_URI_ALL);
			cur = cr.query(uri, projection, "address=? or address=?", new String[] { phone, num }, "date asc");
			if (cur.moveToFirst()) {
				String phoneNumber;
				String smsbody;
				int phoneNumberColumn = cur.getColumnIndex("address");
				int smsbodyColumn = cur.getColumnIndex("body");
				int dateColumn = cur.getColumnIndex("date");
				int typeColumn = cur.getColumnIndex("type");
				do {
					SMS sms = new SMS();
					phoneNumber = cur.getString(phoneNumberColumn);
					smsbody = cur.getString(smsbodyColumn);
					int typeId = cur.getInt(typeColumn);
					sms.setPhoneNum(phoneNumber);
					sms.setTime(cur.getString(dateColumn));
					sms.setId(cur.getLong(0));
					sms.setThreadId(cur.getLong(1));
					sms.setBody(smsbody);
					sms.setType(typeId);
					list.add(sms);
				} while (cur.moveToNext());
			}

		} catch (SQLiteException ex) {
			Log.d("SQLiteException in getSmsInPhone", ex.getMessage());
		} finally {
			if (cur != null) {
				cur.close();
			}
		}
		return list;
	}

	/**
	 * 插入短信.
	 * @param phoneNum 号码
	 * @param body  内容
	 * @param type  插入类型
	 * @param time 时间
	 * @return boolean
	 */
	public static boolean insert(Context context, String phoneNum, String body, int type, String time) {
		try {
			ContentValues values = new ContentValues();
			values.put("address", phoneNum);
			values.put("read", 1);
			values.put("status", -1);
			values.put("type", type);
			values.put("body", body);
			values.put("date", time);
			Uri url = Uri.parse("content://sms/inbox");
			if (type == 2) {
				url = Uri.parse("content://sms/sent");
			}
			ContentResolver myContentResolver = context.getContentResolver();
			myContentResolver.insert(url, values);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 修改短信内容
	 * 
	 * @param threadId
	 *            thread_id
	 * @param id
	 *            id
	 * @param time
	 *            时间
	 * @param body
	 *            内容
	 * @param type
	 *            短信类型
	 * @param phoneNum
	 *            号码
	 * @return boolean
	 */
	public static boolean save(Context context, String threadId, String id, String time, String body, int type,
			String phoneNum) {
		try {
			ContentValues values = new ContentValues();
			values.put("address", phoneNum);
			values.put("_id", id);
			values.put("thread_id", threadId);
			values.put("read", 1);
			values.put("status", -1);
			values.put("type", type);
			values.put("body", body);
			values.put("date", time);
			ContentResolver myContentResolver = context.getContentResolver();
			myContentResolver.update(Uri.parse("content://sms/conversations/" + threadId), values, "_id=?",
					new String[] { id });
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}
